/**
 * Copyright (C) 2014
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package psn.shan.xml.enhancedvalidator.rules;

import java.util.Collection;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.tuple.Pair;
import org.springframework.context.annotation.Scope;

import psn.shan.xml.enhancedvalidator.data.GenericRelationAccessor;
import psn.shan.xml.enhancedvalidator.data.RelationAccessorFactory;
import psn.shan.xml.enhancedvalidator.data.Tuple;

/**
 * RuleSourceAdaptorImpl <br />
 *
 * A RuleSourceAdaptor implementation restricted to Strings
 * 
 * @author Shan
 * 
 */
@Named("RuleSourceAdaptor")
@Scope("prototype")
@Slf4j
public class RuleSourceAdaptorImpl implements RuleSourceAdaptorIfc<String> {

	@Inject
	private RelationAccessorFactory mRelationAccessorFactory;
	
	GenericRelationAccessor<String, Tuple<String>, ?> mRelAccessor;
	
	public void setAccessor(String aAccessor) {
		log.debug("Requesting accessor " + aAccessor);
		mRelAccessor = mRelationAccessorFactory.getAccessor(aAccessor);
		log.debug("Attributes are " + mRelAccessor.getAttributeNames());
	}

	@Override
	public boolean exists(String aKey) {
		log.debug("Checking existence of " + aKey + " using accessor " + mRelAccessor);
		log.debug("Attributes are " + mRelAccessor.getAttributeNames());
		return mRelAccessor.exists(aKey);
	}
	
	@Override
	public boolean exists(String aKey, @SuppressWarnings("unchecked") Pair<String, String>... aValues) {
		Collection<Tuple<String>> lValues = mRelAccessor.getValues(aKey);
		List<String> lNames = mRelAccessor.getAttributeNames();
		if (lValues != null) {
			for (Pair<String, String> lValueToCheck : aValues) {
				int lIndex = lNames.indexOf(lValueToCheck.getLeft());
				for (Tuple<String> lValue : lValues) {			
					if (lValue.getAttributeValues().get(lIndex).getValue().equals(lValueToCheck.getRight())) {
						return true;
					}
				}			
			}
		}
		return false;
	}

	@Override
	public boolean canExist(String aKey, String aValue) {
		return false;
	}

	@Override
	public boolean mustExist(String aKey, String aValue) {
		return false;
	}
}
